<template>
   <el-dialog :model-value="props.GiveRolesDialog" title="分配角色" :before-close="() => emit('showGiveRolesDialog', false)">
    <el-tree :data="treeData" :props="defaultProps" show-checkbox node-key="id" :default-checked-keys="defkeys" @check="treeCheck"/>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="emit('showGiveRolesDialog', false)">取消</el-button>
        <el-button type="primary" @click="roleOk">确定</el-button>
      </span>
    </template>
   </el-dialog>
</template>

<script lang="ts" setup>
import { ShowRightFnc, SetRightFnc } from '@/api/roles'
import { ref, watch } from 'vue';

const emit = defineEmits(['showGiveRolesDialog', 'init'])
const props = defineProps({
   GiveRolesDialog: {type: Boolean, required: true},
   row: {type: Object, required: true}
})
const treeData = ref([]) // tree数据
const defkeys = ref<any>([]) // 默认选中的节点ID数值
const defaultProps = ref({children: 'children', label: 'authName'})
const ID = ref(0)

// 通过递归的形式获取角色下所有三级权限的ID并保存到数组中
const getLeafKeys = (node: any, arr: number[]) => { 
  if (!node.children) {
    if (arr.includes(node.id)) {
      return false
    } else {
      return arr.push(node.id) // 将number转为字符串
    }
  }
  node.children.forEach((item: {children: [], id: number}) => {
    getLeafKeys(item, arr)
  })
}

watch(() => props.GiveRolesDialog, async () => {
  const res = await ShowRightFnc()
  if(res.data.meta.status === 200) {
    treeData.value = res.data.data
    getLeafKeys(props.row, defkeys.value)
  }
  ID.value = props.row.id
})

// 权限树点击选择
const treeCheck = (_:any, obj: {checkedKeys: [], halfCheckedKeys: []}) => {
  const arr = [...obj.checkedKeys, obj.halfCheckedKeys]
  defkeys.value = arr
}

// 分配权限
const roleOk = async () => {
  const rids = defkeys.value.join(',')
  const res = await SetRightFnc(ID.value, { rids: rids } )
  if(res.data.meta.status === 200) {
    ElMessage({type: 'success', message: '更新成功', duration: 1000, onClose: () => {
      emit('showGiveRolesDialog', false)
      emit('init')
    }})
  }
}

</script>